-- TiedPigM
-- Created by panyl
-- 捆绑的野猪

module("TiedPigM", package.seeall);

local startDungeon;
local whenLeaveDungeon;
local whenEnterNext;
local whenSummonDie;

function init()
    -- 开始了地牢
    EventMgr.removeAll("TiedPigM");
end

-- 当前是否有绑猪
function hasTiedPig()
    local summonInfo = ME.user.dbase:query("summon", {});
    local info = FormulaM.invoke("CALC_ROAST_PIG_BONUS", ME.user, true);
    local classId = info["class_id"];

    for _, data in pairs(summonInfo) do
        if data.class_id == classId then
            return true;
        end
    end

    return false;
end

-- 解救野猪
function rescuePig(pos)
    -- 如果该格子不是被烤的野猪
    local grid = DungeonM.getGridByPos(pos);
    if  grid.type ~= GRID_TYPE_TIED_PIG or
        grid.state == GRID_STATE_DISABLE then
        trace("TiedPigM", "不能解救。");
        return false;
    end

    -- 野猪
    local info = FormulaM.invoke("CALC_ROAST_PIG_BONUS", ME.user, true);
    local classId = info["class_id"];

    local result = false;
    -- 能召唤再设置
    if SummonM.canDoSummon(classId) == true then
        -- 野猪生命
        local dugeonId = DungeonM.getDungeonId();
        if dugeonId == nil then
            dugeonId = ME.user.dbase:query("currentDungeon");
        end
        local layerFix = DungeonAreaM.query(dugeonId, "layer_fix");
        local layer =  DungeonM.currentLayer();
        local hp = FormulaM.invoke("CALC_DUNGEON_MONSTER_INIT_HP", 20, layer, layerFix);

        -- 记录一下，出副本之后再召唤(SummonM中处理)
        local toBeSummon = ME.user.dbase:query("to_be_summon", {});
        table.insert(toBeSummon, {["class_id"] = classId, ["hp"] = hp});
        ME.user.dbase:set("to_be_summon", toBeSummon);
        result = true;
    end

    grid:changeState(GRID_STATE_DISABLE);

    -- 抛出解救事件
    EventMgr.fire(event.RESCUE_PIG, {["result"] = result});

    if DungeonM.isCostRound(grid) then
        -- 抛出一个回合事件
        EventMgr.fire(event.COMBAT_ROUND, pos);
    end

    return true;
end
